package com.fenghuajueli.module_user.activity.login;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.TouchDelegate;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants;
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity;
import com.fenghuajueli.lib_statistics.UmEventConstant;
import com.fenghuajueli.lib_statistics.UmEventUtils;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.ui.PrivacyWebActivity;
import com.fenghuajueli.libbasecoreui.upload.UploadUtils;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.constants.PrivacyConstantsUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.utils.RouteUtils;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.R;
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity;
import com.fenghuajueli.module_user.databinding.ActivityLoginBinding;
import com.fenghuajueli.module_user.dialog.PrivacyTipDialog;
import com.fenghuajueli.module_user.model.UserViewModel;
import com.fenghuajueli.module_user.network.result.TemplateResult;
import com.fenghuajueli.module_user.network.model.template.ThemeColor;
import com.fenghuajueli.module_user.ui.refund.RefundActivity;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

@Route(path = UserModuleRoute.USER_LOGIN)
public class LoginActivity extends UserViewModelBaseActivity implements View.OnClickListener {
    private boolean pwdIsShow = false;

    ActivityLoginBinding binding;

    /**
     * 传递过来的需要跳转到vip页面参数的值 type的值等于这个才跳转到vip开通页面
     */
    private static final String NEED_TO_VIP = "needToVip";

    /**
     * 此参数用来判断登录成功之后是否跳转到vip购买页面
     * ，根据运营需求来传递
     */
    @Autowired(name = "type")
    String type = "";
    /**
     * 此参数只是统计事件才用到的，不是项目通用参数
     */
    @Autowired(name = RouteUtils.PARAMETER_FUN_TYPE)
    int funType = 0;

    /**
     * 按运营需求加入退款申请先登录后，接下来需要直接进到“退款申请页”
     */
    @Autowired(name = "refund")
    boolean shouldRefund = false;

    private final UserViewModel userViewModel = new UserViewModel();

    /**
     * 用户是否勾选了同意用户协议等
     */
    public static final String KEY_APPLY_PRIVACY = "login_apply_privacy";
    /**
     * 一键登录SDK是否初始化
     */
    private boolean initOnekeySdk = false;


    @Override
    public BaseViewModel setBaseViewModel() {
        return userViewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EventBus.getDefault().register(this);
        initPrivacy();
        initLogo();
        initClick();
        userViewModel.setUploadCallback(() -> {
            UploadUtils.registerAction(LoginActivity.this, getApplication(), true);
        });
        userViewModel.oneKeyLoginAuthSuccess.observe(this, accessToken -> {
            if (!TextUtils.isEmpty(accessToken)) {
                userViewModel.loginByAccessToken(LoginActivity.this, accessToken, type);
            }
        });

        if (TextUtils.isEmpty(AppConfigInfo.WECHAT_APP_ID) || AppConfigInfo.WECHAT_APP_ID.startsWith("xxxx")
                || TextUtils.isEmpty(AppConfigInfo.WECHAT_APP_SECRET) || AppConfigInfo.WECHAT_APP_SECRET.startsWith("xxxx")) {
            binding.llOtherLogin.setVisibility(View.GONE);
            binding.tvWxLogin.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(AppConfigInfo.ALI_LOGIN_KEY) || AppConfigInfo.ALI_LOGIN_KEY.startsWith("xxxx")) {
            binding.btnOneKeyLogin.setVisibility(View.GONE);
        }
        userViewModel.templateResult.observe(this, result -> {
            if (result instanceof TemplateResult.Success){
                ThemeColor themeColor = ((TemplateResult.Success) result).getData().getTheme_color();
                binding.btnLogin.getBackground().setTint(Color.parseColor(themeColor.getTheme_colors()));
                binding.btnOneKeyLogin.getBackground().setTint(Color.parseColor(themeColor.getAuxiliary_color()));
            }
        });
    }

    @Override
    protected void initStatusBarColor() {
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.loginStatusBarColor));
        BarUtils.setStatusBarLightMode(this, AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_NO);
    }

    private void initClick() {
        binding.btnLogin.setOnClickListener(this);
        binding.ivClose.setOnClickListener(this);
        binding.tvRegister.setOnClickListener(this);
        binding.tvForgetPassword.setOnClickListener(this);
        binding.tvWxLogin.setOnClickListener(this);
        binding.ivChangePwdStatus.setOnClickListener(this);
        binding.btnOneKeyLogin.setOnClickListener(this);
        binding.checkView.setOnClickListener(this);
        binding.checkView.setSelected(checkAgree());
        expendTouchArea(binding.checkView, ConvertUtils.dp2px(150));
    }

    /**
     * 初始化协议相关
     */
    private void initPrivacy() {
        String first = "阅读并同意 ";
        String second = "《用户协议》";
        String third = "《隐私政策》";
        SpannableString spannableString = new SpannableString(first + second + "和" + third);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(LoginActivity.this, R.color.priviceTextColor));
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(LoginActivity.this, PrivacyConstantsUtils.ProtocolType.USER_PROTOCOL);
            }
        };
        spannableString.setSpan(clickableSpan, first.length(), first.length() + second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(LoginActivity.this, R.color.priviceTextColor));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(LoginActivity.this, PrivacyConstantsUtils.ProtocolType.PRIVACY);
            }
        };
        spannableString.setSpan(clickableSpan, first.length() + second.length() + 1, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvPrivacy.setText(spannableString);
        binding.tvPrivacy.setHighlightColor(Color.TRANSPARENT);
        binding.tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());

        //儿童隐私保护声明
        childrenPrivacy();
    }

    /**
     * 儿童隐私保护声明
     */
    private void childrenPrivacy() {
        ClickableSpan clickableSpan;
        SpannableString childrenSpannableString = new SpannableString("《儿童隐私保护声明》");
        clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ContextCompat.getColor(LoginActivity.this, R.color.priviceTextColor));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(LoginActivity.this, PrivacyConstantsUtils.ProtocolType.CHILDREN_PRIVACY);
            }
        };
        childrenSpannableString.setSpan(clickableSpan, 0, childrenSpannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvChildrenPrivacy.setText(childrenSpannableString);
        binding.tvChildrenPrivacy.setHighlightColor(Color.TRANSPARENT);
        binding.tvChildrenPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
    }


    @Override
    public void onClick(View view) {
        if (QuickClickUtils.isFastClick()) {
            return;
        }
        int viewId = view.getId();
        if (viewId == R.id.btnLogin || viewId == R.id.tvRegister || viewId == R.id.tvForgetPassword || viewId == R.id.tvWxLogin || viewId == R.id.btnOneKeyLogin) {
            //这些按钮需要检测是否同意协议
            if (!checkAgree()) {
                showPrivacyTipDialog(viewId);
                return;
            }
        }

        if (viewId == R.id.ivClose) {
            finish();
        } else if (viewId == R.id.ivChangePwdStatus) {
            if (pwdIsShow) {
                binding.etInputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                binding.ivChangePwdStatus.setImageResource(R.mipmap.aa_icon_to_view);
            } else {
                binding.etInputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                binding.ivChangePwdStatus.setImageResource(R.mipmap.aa_icon_close_look_at);
            }
            pwdIsShow = !pwdIsShow;
            binding.etInputPassword.postInvalidate();
        } else if (viewId == R.id.checkView) {
            saveAgreeStatus(!checkAgree());
            binding.checkView.setSelected(checkAgree());
        } else {
            checkFunctionClick(viewId);
        }
    }

    private void checkFunctionClick(int viewId) {
        if (viewId == R.id.btnLogin) {
            UmEventUtils.onEvent(UmEventConstant.login_count);
            login();
        } else if (viewId == R.id.tvRegister) {
            ARouter.getInstance().build(UserModuleRoute.USER_REGISTER).navigation();
        } else if (viewId == R.id.tvForgetPassword) {
            ARouter.getInstance().build(UserModuleRoute.USER_FORGET_PASSWORD).navigation();
        } else if (viewId == R.id.tvWxLogin) {
            wxLogin();
        } else if (viewId == R.id.btnOneKeyLogin) {
            userViewModel.checkOneKeyLoginEnv();
        }
    }

    private void showPrivacyTipDialog(int viewId) {
        PrivacyTipDialog privacyTipDialog = new PrivacyTipDialog(this);
        privacyTipDialog.setOnButtonClickListener(new PrivacyTipDialog.OnButtonClickListener() {
            @Override
            public void onLeftButtonClick() {

            }

            @Override
            public void onRightButtonClick() {
                saveAgreeStatus(true);
                binding.checkView.setSelected(checkAgree());
                checkFunctionClick(viewId);
            }
        });
        privacyTipDialog.show();
    }

    private void wxLogin() {
        if (userViewModel != null) {
            userViewModel.wxLogin(this, type);
        }
    }

    private void login() {
        if (userViewModel != null) {
            userViewModel.loginByPhone(this, type, binding.etInputPhone.getText().toString().trim(), binding.etInputPassword.getText().toString().trim());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.REGISTER_SUCCESS) {
            if (!TextUtils.isEmpty(type) && NEED_TO_VIP.equals(type)) {
                //从评论对话框来的需要跳转至购买页面
                RouteUtils.routeToOpenVip();
            }
            finish();
        }
        if (eventBusEntity.getCode() == EventBusConstants.LOGIN_SUCCESS) {
            if (shouldRefund){
                RefundActivity.start(this);
            }
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (userViewModel != null) {
            userViewModel.destroyOneKeyLogin();
        }
        EventBus.getDefault().unregister(this);
    }

    public void saveAgreeStatus(boolean agree) {
        if (agree && !initOnekeySdk) {
            initOnekeySdk = true;
            userViewModel.initOneKeyLogin(getApplication(), AppConfigInfo.ALI_LOGIN_KEY, false);
        }
        MmkvUtils.save(KEY_APPLY_PRIVACY, agree);
    }

    public boolean checkAgree() {
        boolean agree = MmkvUtils.get(KEY_APPLY_PRIVACY, false);
        if (agree && !initOnekeySdk) {
            initOnekeySdk = true;
            userViewModel.initOneKeyLogin(getApplication(), AppConfigInfo.ALI_LOGIN_KEY, false);
        }
        return agree;
    }

    public void expendTouchArea(final View view, final int expendSize) {
        if (view != null) {
            final View parentView = (View) view.getParent();

            parentView.post(() -> {
                Rect rect = new Rect();
                view.getHitRect(rect); //如果太早执行本函数，会获取rect失败，因为此时UI界面尚未开始绘制，无法获得正确的坐标
                rect.left -= expendSize;
                rect.top -= expendSize;
                rect.right += expendSize;
                rect.bottom += expendSize;
                parentView.setTouchDelegate(new TouchDelegate(rect, view));
            });
        }
    }

    private void initLogo() {
        RoundedCorners corners = new RoundedCorners(ConvertUtils.dp2px(20));
        Glide
                .with(this)
                .load(AppUtils.getAppIcon())
                .apply(RequestOptions.bitmapTransform(corners))
                .into(binding.ivLogo);
    }
}